package com.itheima.filter;

import com.itheima.common.utils.JwtUtil;
import com.itheima.pojo.User;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        // 从请求头获取Authorization
        String authHeader = request.getHeader("Authorization");
        String token;

        // 处理Bearer令牌
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            token = authHeader.substring(7); // 去掉"Bearer "前缀
        } else {
            // 尝试从请求参数获取
            token = request.getParameter("token");
        }

        if (token == null || token.isEmpty()) {
            filterChain.doFilter(request, response);
            return;
        }

        try {
            // 解析token获取手机号
            Claims claims = JwtUtil.parseJWT("wh_study", token);
            String telephone = (String) claims.get("userId");

            // 从Redis获取用户
            User loginUser = (User) redisTemplate.opsForValue().get("login:" + telephone);

            if (loginUser == null) {
                // 返回401而不是抛出异常
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                return;
            }

            // 将信息存入SecurityContextHolder
            SecurityContextHolder.getContext().setAuthentication(
                    new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities())
            );
        } catch (Exception e) {
            // 令牌无效时返回401
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }

        // 放行
        filterChain.doFilter(request, response);
    }
}
